/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Button, Classes, Dialog, Intent } from '@blueprintjs/core';
import { IconNames } from '@blueprintjs/icons';
import React, { useState } from 'react';

import { AutoForm } from '../../components';
import {
  WEB_CONSOLE_CONFIG_FIELDS,
  type WebConsoleConfig,
} from '../../druid-models/web-console-config/web-console-config';
import { DEFAULT_WEB_CONSOLE_CONFIG } from '../../druid-models/web-console-config/web-console-config.mock';
import { AppToaster } from '../../singletons';
import { localStorageGetJson, LocalStorageKeys, localStorageSetJson } from '../../utils';

export interface WebConsoleConfigDialogProps {
  onClose(): void;
}

export const WebConsoleConfigDialog = React.memo(function WebConsoleConfigDialog(
  props: WebConsoleConfigDialogProps,
) {
  const { onClose } = props;
  const [config, setConfig] = useState<WebConsoleConfig>(
    localStorageGetJson(LocalStorageKeys.WEB_CONSOLE_CONFIGS) || DEFAULT_WEB_CONSOLE_CONFIG,
  );

  function save() {
    localStorageSetJson(LocalStorageKeys.WEB_CONSOLE_CONFIGS, config);
    AppToaster.show({
      message: 'Saved web console config',
      intent: Intent.SUCCESS,
    });
    onClose();
    location.reload();
  }

  return (
    <Dialog isOpen title="Web console config" onClose={onClose} canOutsideClickClose={false}>
      <div className={Classes.DIALOG_BODY}>
        <p>Sets the local web console configuration.</p>
        <AutoForm fields={WEB_CONSOLE_CONFIG_FIELDS} model={config} onChange={setConfig} />
      </div>
      <div className={Classes.DIALOG_FOOTER}>
        <div className={Classes.DIALOG_FOOTER_ACTIONS}>
          <Button text="Save" onClick={save} intent={Intent.PRIMARY} rightIcon={IconNames.TICK} />
        </div>
      </div>
    </Dialog>
  );
});
